import 'dart:io';

import 'package:dio/dio.dart';

main(List<String> args) {
  multiUpload();
}

Dio _buildDio() {
  Map<String, dynamic> headers = Map();
  headers['Authorization'] = "Bearer 4da685bf-bee3-4fb0-a3d4-a12701bab089";
  Dio dio = Dio(BaseOptions(
    baseUrl: "http://localhost:7000",
    headers: headers,
    connectTimeout: 5000,
    receiveTimeout: 3000,
  ));

  dio.interceptors
      .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
    print(options.contentType);
    return options;
    // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
    // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
    // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
    // 这样请求将被中止并触发异常，上层catchError会被调用。
  }, onResponse: (Response response) async {
    // 在返回响应数据之前做一些预处理
    return response;
  }, onError: (DioError e) async {
    // 当请求失败时做一些预处理
    return e;
  }));
  return dio;
}

_onSendProgress(int sent, int total) {
  print("$sent $total");
}

multiUpload() async {
  Dio dio = _buildDio();

  FormData formData = FormData();
  formData.files.addAll([
    MapEntry(
      "files",
      MultipartFile.fromFileSync("./text1.txt", filename: "text1.txt"),
    ),
    MapEntry(
      "files",
      MultipartFile.fromFileSync("./text2.txt", filename: "text2.txt"),
    ),
  ]);

  Response response = await dio.post("/api/v1/file/upload2",
      data: formData, onSendProgress: _onSendProgress);
  print(response.data);
}

singleUpload() async {
  Dio dio = _buildDio();
  MultipartFile multipartFile =
      await MultipartFile.fromFile('./text1.txt', filename: 'text1.txt');
  FormData formData = FormData.fromMap({"files": multipartFile});
  Response response = await dio.post("/api/v1/file/upload2",
      data: formData, onSendProgress: _onSendProgress);
  print(response.data);
}
